package com.haierp.service.item.impl;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.model.OSSObject;
import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.haierp.enums.ItemStatus;
import com.haierp.enums.PlatformType;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.OuterItemMapper;
import com.haierp.mapper.OuterItemSkuMapper;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItem;
import com.haierp.model.item.OuterItemSku;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IUploadFileService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.service.youzan.IYzService;
import com.haierp.vo.ItemQueryVO;
import com.haierp.vo.json.PicModel;
import com.haierp.vo.youzan.ItemImages;
import com.wangzhixuan.commons.utils.HaiJsonUtils;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemCreateParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemCreateResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemCreateResult.ItemSkuOpenModel;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemGetParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemSkuUpdateParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemUpdateDelistingParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemUpdateListingParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemUpdateParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemUpdateResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanMaterialsStoragePlatformImgUploadParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanMaterialsStoragePlatformImgUploadResult;
import com.youzan.open.sdk.model.ByteWrapper;

@Service
public class OuterItemServiceImpl extends SuperServiceImpl<OuterItemMapper, OuterItem> implements IOuterItemService {

	@Autowired
	private IItemService itemService;
	@Autowired
	private IUploadFileService uploadFileService;
	@Autowired
	private IYzService yzService;
	@Autowired
	private OuterItemSkuMapper outerItemSkuMapper;
	@Autowired
	private  IInventoryService inventoryService;
	@Override
	public void synItemYouzan(Long itemId) {
		ItemQueryVO itemQueryVO = new ItemQueryVO();
		itemQueryVO.setItemId(itemId);
		Item item = itemService.queryItem(itemQueryVO);
		if(item.getYzisSale()==0) {
			return;
		}
		if(item.getCompanyId()!=1){
			throw new ErpCommonException("商品代码："+item.getItemCode()+"商品不能执行此操作！");
		}
		if(item.getStatus()==ItemStatus.INIT.getCode()){ //未同步过
			//构造上传的商品对象
			YouzanItemCreateParams youzanItemCreateParams = createYouzanAddItem(item);
			YouzanItemCreateResult youzanItemCreateResult = yzService.youzanItemCreate(youzanItemCreateParams);
			
			item.setImageIds(youzanItemCreateParams.getImageIds());
			addOuterItem(item, youzanItemCreateResult);
		}else{//已同步过
			if(item.getStatus()!=ItemStatus.LISTING.getCode()){
				throw new ErpCommonException("商品代码："+item.getItemCode()+"下架商品不能同步");
			}
			//构造上传的商品对象
			OuterItem outerItemQuery= new OuterItem();
			outerItemQuery.setItemId(itemId);
			outerItemQuery.setPlatformType(PlatformType.YOUZAN.getCode());
			OuterItem outerItem = this.baseMapper.selectOne(outerItemQuery);
			if(outerItem!=null){
				YouzanItemUpdateParams youzanItemUpdateParams = createYouzanUpdateItem(item);
				youzanItemUpdateParams.setItemId(outerItem.getOuterId());
				youzanItemUpdateParams.setRemoveImageIds(outerItem.getImageIds());
				YouzanItemUpdateResult youzanItemUpdateResult = yzService.youzanItemUpdate(youzanItemUpdateParams);
				
				item.setImageIds(youzanItemUpdateParams.getImageIds());
				updateOuterItem(item, youzanItemUpdateResult);
			}else{
				throw new ErpCommonException("有赞商品有误");
			}
		}
	}

	private void updateOuterItem(Item item, YouzanItemUpdateResult youzanItemUpdateResult) {
		//String alias = youzanItemUpdateResult.getItem().getAlias();//有赞别名
		Long numIid = youzanItemUpdateResult.getItemId();//有赞ID
		//1、保存外部商品
		OuterItem outerItem = new OuterItem();
		outerItem.setItemId(item.getId());
		outerItem.setPlatformType(PlatformType.YOUZAN.getCode());
		OuterItem outerItemDb = this.baseMapper.selectOne(outerItem);
		if(outerItemDb==null){
			throw new ErpCommonException("更新outerItem 订单信息错误");
		} else {
			outerItemDb.setImageIds(item.getImageIds());
			this.baseMapper.updateSelectiveById(outerItemDb);
		}
		List<ItemSku> itemSkuList = item.getItemSkus();
		Map<String, Long> itemSkuIdMap = new HashMap<String, Long>();
		for(ItemSku itemSku : itemSkuList) {
			itemSkuIdMap.put(itemSku.getSkuCode(), itemSku.getId());
		}
			
		//2、更新外部SKU信息
		YouzanItemGetParams youzanItemGetParams = new YouzanItemGetParams();
		youzanItemGetParams.setItemId(outerItemDb.getOuterId());
		youzanItemGetParams.setAlias(outerItemDb.getOuterAlias());
		YouzanItemGetResult itemGetResult = yzService.youzanItemGet(youzanItemGetParams);	
		com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemGetResult.ItemSkuOpenModel[] goodsSku = itemGetResult.getItem().getSkus();
		if(goodsSku!=null && goodsSku.length>0){
			for(int i=0;i<goodsSku.length;i++) {
				com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemGetResult.ItemSkuOpenModel sku = goodsSku[i];
				if(StringUtil.isBlank(sku.getItemNo()) || itemSkuIdMap.get(sku.getItemNo())==null) {
					continue;
				}
				OuterItemSku outerItemSku = new OuterItemSku();
				outerItemSku.setSkuId(itemSkuIdMap.get(sku.getItemNo()));
				outerItemSku.setPlatformType(PlatformType.YOUZAN.getCode());
				OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
				outerItemSku.setItemId(item.getId());
				outerItemSku.setOuterId(numIid);
				outerItemSku.setOuterSkuId(sku.getSkuId());
				outerItemSku.setOuterItemId(outerItemDb.getId());
				outerItemSku.setSkuCode(sku.getItemNo());
				if(selOuterItemSku == null) {
					outerItemSkuMapper.insert(outerItemSku);
				} else {
					outerItemSku.setId(selOuterItemSku.getId());
					outerItemSkuMapper.updateSelectiveById(outerItemSku);
				}
			}
		}
		
	}

	/**
	 * 新增外部商品和SKU信息
	 * @param item
	 * @param YouzanItemCreateResult
	 */
	private void addOuterItem(Item item, YouzanItemCreateResult youzanItemCreateResult) {
		String alias = youzanItemCreateResult.getItem().getAlias();//有赞别名
		Long numIid = youzanItemCreateResult.getItem().getItemId();//有赞ID
		//1、保存外部商品
		OuterItem outerItem = new OuterItem();
		outerItem.setItemId(item.getId());
		outerItem.setPlatformType(PlatformType.YOUZAN.getCode());
		OuterItem selOuterItem = this.baseMapper.selectOne(outerItem);
		outerItem.setOuterAlias(alias);
		outerItem.setOuterId(numIid);
		outerItem.setStatus(ItemStatus.LISTING.getCode());//上架
		outerItem.setImageIds(item.getImageIds());
		if(selOuterItem == null) {
			this.baseMapper.insert(outerItem);
		} else {
			outerItem.setId(selOuterItem.getId());
			this.baseMapper.updateSelectiveById(outerItem);
		}
		
		List<ItemSku> itemSkuList = item.getItemSkus();
		Map<String, Long> itemSkuIdMap = new HashMap<String, Long>();
		for(ItemSku itemSku : itemSkuList) {
			itemSkuIdMap.put(itemSku.getSkuCode(), itemSku.getId());
		}
		
		//2、更新外部SKU信息
		ItemSkuOpenModel[]goodsSku =   youzanItemCreateResult.getItem().getSkus();
		if(goodsSku!=null&&goodsSku.length>0){
			for(int i=0;i<goodsSku.length;i++) {
				ItemSkuOpenModel sku = goodsSku[i];
				if(StringUtil.isBlank(sku.getItemNo()) || itemSkuIdMap.get(sku.getItemNo())==null) {
					continue;
				}
				OuterItemSku outerItemSku = new OuterItemSku();
				outerItemSku.setSkuId(itemSkuIdMap.get(sku.getItemNo()));
				outerItemSku.setPlatformType(PlatformType.YOUZAN.getCode());
				OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
				outerItemSku.setItemId(item.getId());
				outerItemSku.setOuterId(numIid);
				outerItemSku.setOuterSkuId(sku.getSkuId());
				outerItemSku.setOuterItemId(outerItem.getId());
				outerItemSku.setSkuCode(sku.getItemNo());
				if(selOuterItemSku == null) {
					outerItemSkuMapper.insert(outerItemSku);
				} else {
					outerItemSku.setId(selOuterItemSku.getId());
					outerItemSkuMapper.updateSelectiveById(outerItemSku);
				}
			}
		}
		
		//3、更新erp商品信息
		item.setStatus(ItemStatus.LISTING.getCode());
		item.setGmtModify(new Date());
		itemService.updateById(item);
		
	}

	private YouzanItemCreateParams createYouzanAddItem(Item item) {
		YouzanItemCreateParams youzanItemCreateParams = new YouzanItemCreateParams();
		youzanItemCreateParams.setTitle(item.getName());
		if(StringUtils.isNotEmpty(item.getDetail())){
			try {
				//String decodeStr = URLDecoder.decode(item.getDetail(),"UTF-8"); 
				youzanItemCreateParams.setDesc(item.getDetail());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			youzanItemCreateParams.setDesc(item.getName());
		}
		if(item.getFreight()!=null && item.getFreight()>0) {
			youzanItemCreateParams.setPostFee((long)(item.getFreight()*100));
		} else {
			youzanItemCreateParams.setPostFee(0L);
		}
		//图片
		String itemPic = item.getMainPic();
		ItemImages itemImages = initImages( itemPic);
		if(itemImages != null) {
			ByteWrapper[] byteWrapperArr = itemImages.getByteWrappers();
			String imageIds = null;
			for(int i=0; i<byteWrapperArr.length; i++) {
				ByteWrapper[] pByteWrapperArr = new ByteWrapper[1];
				pByteWrapperArr[0] = byteWrapperArr[i];
				YouzanMaterialsStoragePlatformImgUploadParams youzanMaterialsStoragePlatformImgUploadParams = new YouzanMaterialsStoragePlatformImgUploadParams();
				youzanMaterialsStoragePlatformImgUploadParams.setImage(pByteWrapperArr);
				YouzanMaterialsStoragePlatformImgUploadResult result = yzService.youzanMaterialsStoragePlatformImgUpload(youzanMaterialsStoragePlatformImgUploadParams);
				if(imageIds == null) {
					imageIds = result.getImageId().toString();
				} else {
					imageIds += "," + result.getImageId().toString();
				}
			}
			youzanItemCreateParams.setImageIds(imageIds);
		}
		
		youzanItemCreateParams.setItemNo(item.getItemCode());
		//SKU
		 List<ItemSku> itemSkus = item.getItemSkus();
		//List<YouZanSku> youZanSkuList = initSkuJson(itemSkus);
		 List<Map<String,Object>> youZanSkuList = initSkuJsonOne(itemSkus);
		 if(CollectionUtils.isNotEmpty(youZanSkuList)){
			 String skusWithJson = HaiJsonUtils.toJson(youZanSkuList);
			 youzanItemCreateParams.setSkuStocks(skusWithJson);
		 }         
		 Double minSalePrice = itemSkus.get(0).getSalePrice();
		 for (ItemSku itemSku : itemSkus) {
			 if(itemSku.getSalePrice()<minSalePrice){
				 minSalePrice = itemSku.getSalePrice();
			 }
		}
		 youzanItemCreateParams.setPrice((long)(minSalePrice*100));
		return youzanItemCreateParams;
	}

	private YouzanItemUpdateParams createYouzanUpdateItem(Item item) {
		YouzanItemUpdateParams youzanItemUpdateParams = new YouzanItemUpdateParams();
		youzanItemUpdateParams.setTitle(item.getName());
		if(StringUtils.isNotEmpty(item.getDetail())){
			try {
				//String decodeStr = URLDecoder.decode(item.getDetail(),"UTF-8"); 
				youzanItemUpdateParams.setDesc(item.getDetail());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(item.getFreight()!=null && item.getFreight()>0) {
			youzanItemUpdateParams.setPostFee((long)(item.getFreight()*100));
		} else {
			youzanItemUpdateParams.setPostFee(0L);
		}
		//图片
		String itemPic = item.getMainPic();
		ItemImages itemImages = initImages( itemPic);
		if(itemImages != null) {
			ByteWrapper[] byteWrapperArr = itemImages.getByteWrappers();
			String imageIds = null;
			for(int i=0; i<byteWrapperArr.length; i++) {
				ByteWrapper[] pByteWrapperArr = new ByteWrapper[1];
				pByteWrapperArr[0] = byteWrapperArr[i];
				YouzanMaterialsStoragePlatformImgUploadParams youzanMaterialsStoragePlatformImgUploadParams = new YouzanMaterialsStoragePlatformImgUploadParams();
				youzanMaterialsStoragePlatformImgUploadParams.setImage(pByteWrapperArr);
				YouzanMaterialsStoragePlatformImgUploadResult result = yzService.youzanMaterialsStoragePlatformImgUpload(youzanMaterialsStoragePlatformImgUploadParams);
				if(imageIds == null) {
					imageIds = result.getImageId().toString();
				} else {
					imageIds += "," + result.getImageId().toString();
				}
			}
			youzanItemUpdateParams.setImageIds(imageIds);
		}
		//SKU
		 List<ItemSku> itemSkus = item.getItemSkus();
		//List<YouZanSku> youZanSkuList = initSkuJson(itemSkus);
		 List<Map<String,Object>> youZanSkuList = initSkuJsonOne(itemSkus);
		 if(CollectionUtils.isNotEmpty(youZanSkuList)){
			 String skusWithJson = HaiJsonUtils.toJson(youZanSkuList);
			 youzanItemUpdateParams.setSkuStocks(skusWithJson);
		 }
		 Double minSalePrice = itemSkus.get(0).getSalePrice();
		 for (ItemSku itemSku : itemSkus) {
			 if(itemSku.getSalePrice() < minSalePrice){
				 minSalePrice = itemSku.getSalePrice();
			 }
		}
		 youzanItemUpdateParams.setPrice((long)(minSalePrice*100));
		return youzanItemUpdateParams;
	}

//	private List<YouZanSku> initSkuJson(List<ItemSku> itemSkus) {
//		List<YouZanSku> youZanSkuList = Lists.newArrayList();
//		if(CollectionUtils.isNotEmpty(itemSkus)){
//			for(ItemSku itemSku:itemSkus){
//				YouZanSku yzs = new  YouZanSku();
//				yzs.setItemNo(itemSku.getSkuCode());//重点：这里的sku_item_no对应的有赞 outer_id
//				yzs.setPrice(itemSku.getSalePrice());
//				int skuQuantity = 0;
//				int lockedVirtualInv = itemSku.getLockedVirtualInv();
//				if(itemSku.getVirtualInv()>0){
//					skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
//				}else{
//					skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
//				}
//				if(skuQuantity<0) skuQuantity = 0;
//				yzs.setQuantity(skuQuantity);
//				
//				if(StringUtil.isNotBlank(itemSku.getColor())) {
//					yzs.getSkus().setColor(itemSku.getColor());
//				}
//				if(StringUtil.isNotBlank(itemSku.getScale())) {
//					yzs.getSkus().setScale(itemSku.getScale());
//				}
//				youZanSkuList.add(yzs);
//			}
//		}else{ 
//			throw new ErpCommonException("没有SKU");
//		}
//		return youZanSkuList;
//	}

	private List<Map<String,Object>> initSkuJsonOne(List<ItemSku> itemSkus) {
		List<Map<String,Object>> youZanSkuList = Lists.newArrayList();
		Map<String, ItemSku> itemSkuMap = Maps.newHashMap();
		Set<String> colorSet = Sets.newHashSet();
		Set<String> scaleSet = Sets.newHashSet();
		if(CollectionUtils.isNotEmpty(itemSkus)){
			for(ItemSku itemSku:itemSkus) {
				String colorScaleKey = "";
				if(StringUtil.isNotBlank(itemSku.getColor())) {
					colorSet.add(itemSku.getColor());
					colorScaleKey += itemSku.getColor();
				}
				if(StringUtil.isNotBlank(itemSku.getScale())) {
					scaleSet.add(itemSku.getScale());
					colorScaleKey += itemSku.getScale();
				}
				itemSkuMap.put(colorScaleKey, itemSku);
			}
			if(colorSet.size()>0 && scaleSet.size()==0) {
				for(String color : colorSet) {
					Map<String,Object> skuStocksMap = new HashMap<String,Object>();
					ItemSku itemSku = itemSkuMap.get(color);
					skuStocksMap.put("price", itemSku.getSalePrice()*100);				
					int skuQuantity = 0;
					int lockedVirtualInv = itemSku.getLockedVirtualInv();
					if(itemSku.getVirtualInv()>0){
						skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
					}else{
						skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
					}
					if(skuQuantity<0) skuQuantity = 0;
					skuStocksMap.put("quantity", skuQuantity);
					skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
					List<Map<String, Object>> skusList = new ArrayList<>();
					Map<String, Object> skusColorMap = new HashMap<String, Object>();
					skusColorMap.put("v", itemSku.getColor());
					skusColorMap.put("k", "颜色");
					skusList.add(skusColorMap);
					
					skuStocksMap.put("skus", skusList);
					youZanSkuList.add(skuStocksMap);
				}
			} else if(scaleSet.size()>0 && colorSet.size()==0) {
				for(String scale : scaleSet) {
					Map<String,Object> skuStocksMap = new HashMap<String,Object>();
					ItemSku itemSku = itemSkuMap.get(scale);
					skuStocksMap.put("price", itemSku.getSalePrice()*100);				
					int skuQuantity = 0;
					int lockedVirtualInv = itemSku.getLockedVirtualInv();
					if(itemSku.getVirtualInv()>0){
						skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
					}else{
						skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
					}
					if(skuQuantity<0) skuQuantity = 0;
					skuStocksMap.put("quantity", skuQuantity);
					skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
					List<Map<String, Object>> skusList = new ArrayList<>();
					Map<String, Object> skusScaleMap = new HashMap<String, Object>();
					skusScaleMap.put("v", itemSku.getScale());
					skusScaleMap.put("k", "尺寸");
					skusList.add(skusScaleMap);
					
					skuStocksMap.put("skus", skusList);
					youZanSkuList.add(skuStocksMap);
				}
			} else {
				for(String color : colorSet) {
					for(String scale : scaleSet) {
						Map<String,Object> skuStocksMap = new HashMap<String,Object>();
						ItemSku itemSku = itemSkuMap.get(color+scale);
						if(itemSku == null) {
							skuStocksMap.put("price", 100000*100);				
							skuStocksMap.put("quantity", 0);
							skuStocksMap.put("item_no", ""); //重点：这里的sku_item_no对应的有赞 outer_id
							List<Map<String, Object>> skusList = new ArrayList<>();
							Map<String, Object> skusColorMap = new HashMap<String, Object>();
							Map<String, Object> skusScaleMap = new HashMap<String, Object>();
							skusColorMap.put("v", color);
							skusColorMap.put("k", "颜色");
							skusList.add(skusColorMap);
							skusScaleMap.put("v", scale);
							skusScaleMap.put("k", "尺寸");
							skusList.add(skusScaleMap);
							
							skuStocksMap.put("skus", skusList);
							youZanSkuList.add(skuStocksMap);
						} else {
							skuStocksMap.put("price", itemSku.getSalePrice()*100);				
							int skuQuantity = 0;
							int lockedVirtualInv = itemSku.getLockedVirtualInv();
							if(itemSku.getVirtualInv()>0){
								skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
							}else{
								skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
							}
							if(skuQuantity<0) skuQuantity = 0;
							skuStocksMap.put("quantity", skuQuantity);
							skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
							List<Map<String, Object>> skusList = new ArrayList<>();
							Map<String, Object> skusColorMap = new HashMap<String, Object>();
							Map<String, Object> skusScaleMap = new HashMap<String, Object>();
							skusColorMap.put("v", itemSku.getColor());
							skusColorMap.put("k", "颜色");
							skusList.add(skusColorMap);
							skusScaleMap.put("v", itemSku.getScale());
							skusScaleMap.put("k", "尺寸");
							skusList.add(skusScaleMap);
							
							skuStocksMap.put("skus", skusList);
							youZanSkuList.add(skuStocksMap);
						}
					}
				}
			}
		}else{ 
			throw new ErpCommonException("没有SKU");
		}
		return youZanSkuList;
	}
	private ItemImages  initImages( String itemPic) {
		if(StringUtils.isNotEmpty(itemPic)){
			ItemImages itemImages = new ItemImages();
			PicModel pm = HaiJsonUtils.toBean(itemPic, PicModel.class);
			ByteWrapper[] byteWrappers = new ByteWrapper[pm.getPicList().size()];
			int i=0;
			StringBuilder sbImgs = new StringBuilder();
			//主图排第一位
			int mainIndex = Integer.valueOf(pm.getMainPicNum())-1;
			Collections.swap(pm.getPicList(), 0, mainIndex);
			
			for(PicModel.PicList pic:pm.getPicList()){
				String url = pic.getUrl();
				String picKey = url;
				if(picKey.contains("?")) {
					picKey = picKey.substring(0, picKey.indexOf("?"));
				}
				picKey = picKey.substring(picKey.lastIndexOf("/")+1);
				
				if(url.contains("aliyuncs.com") && !url.contains("image/resize")) {
					OSSObject ossObject = uploadFileService.getOSSObject(picKey);
					if(ossObject!=null){
						byteWrappers[i] =  new ByteWrapper(picKey,ossObject.getObjectContent(),ContentType.create("image/jpeg"));
					}
				} else {
					try {
						URL urlImg  = new URL(url);
						URLConnection con = urlImg.openConnection();
						con.setConnectTimeout(10*1000);
						byteWrappers[i] =  new ByteWrapper(picKey, con.getInputStream(), ContentType.create("image/jpeg"));
					} catch (Exception e) {
						e.printStackTrace();
					} 
				}
				
				sbImgs.append(picKey.substring(0, picKey.lastIndexOf(".")));
				if(i<(pm.getPicList().size()-1)){
					sbImgs.append(",");
				}
				i++;
			}
			itemImages.setByteWrappers(byteWrappers);
			itemImages.setImageIds(sbImgs.toString());
			return itemImages;
		}
		return null;
	}

	@Override
	public void listingYouzan(Item item) {
		//是否可在有赞销售1可以0不可以
		if(item.getYzisSale()==0) {
			return;
		}
		//查询出第三方平台帐号，上架
		OuterItem outerItemQuery = new OuterItem();
		outerItemQuery.setItemId(item.getId());
		OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
		if(outerItemDb==null){
			throw new ErpCommonException("更新outerItem 订单信息错误;");
		}
		YouzanItemUpdateListingParams youzanItemUpdateListingParams = new YouzanItemUpdateListingParams();
		youzanItemUpdateListingParams.setItemId(outerItemDb.getOuterId());
		yzService.youzanItemUpdateListing(youzanItemUpdateListingParams);
		//更新商品状态
		item.setStatus(ItemStatus.LISTING.getCode());
		item.setGmtModify(new Date());
		itemService.updateById(item);
		//更新外部商品状态
		outerItemDb.setStatus(ItemStatus.LISTING.getCode());
		this.baseMapper.updateById(outerItemDb);
		
	}

	@Override
	public void delistingYouzan(Item item) {
		OuterItem outerItemQuery = new OuterItem();
		outerItemQuery.setItemId(item.getId());
		OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
		if(outerItemDb==null){
			throw new ErpCommonException("更新outerItem 订单信息错误;");
		}
		YouzanItemUpdateDelistingParams youzanItemUpdateDelistingParams = new YouzanItemUpdateDelistingParams();
		youzanItemUpdateDelistingParams.setItemId(outerItemDb.getOuterId());
		yzService.youzanItemUpdateDelisting(youzanItemUpdateDelistingParams);
		//更新商品状态
		item.setStatus(ItemStatus.DELISTING.getCode());
		item.setGmtModify(new Date());
		itemService.updateById(item);
		//更新外部商品状态
		outerItemDb.setStatus(ItemStatus.DELISTING.getCode());
		this.baseMapper.updateById(outerItemDb);
	}

	@Override
	public void synSkuInventory(Long itemId,Long skuId) {
		//查询是否同步到有赞，并且为已上架状态
		OuterItem outerItemQuery = new OuterItem();
		outerItemQuery.setItemId(itemId);
		OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
		if(outerItemDb==null){
//			throw new ErpCommonException("更新outerItem 订单信息错误;");
			this.logger.info("没有找到对应的有赞商品，itemId:"+itemId);
		}
		else{
			//上架中的商品
			if(outerItemDb.getStatus()!=null&&outerItemDb.getStatus()==ItemStatus.LISTING.getCode()){
				OuterItemSku outerItemSkuQuery = new OuterItemSku();
				outerItemSkuQuery.setItemId(itemId);
				outerItemSkuQuery.setSkuId(skuId);
				OuterItemSku outerItemSkuDb = outerItemSkuMapper.selectOne(outerItemSkuQuery);
				if(outerItemSkuDb!=null&&outerItemSkuDb.getOuterSkuId()!=null){
					Inventory inventory=inventoryService.queryInventoryBySkuId(itemId, skuId);
					//同步
					if(inventory!=null){
						YouzanItemSkuUpdateParams youzanItemSkuUpdateParams = new YouzanItemSkuUpdateParams();
						youzanItemSkuUpdateParams.setItemId(outerItemSkuDb.getOuterId());
						youzanItemSkuUpdateParams.setSkuId(outerItemSkuDb.getOuterSkuId());
						youzanItemSkuUpdateParams.setQuantity(inventory.getSysInventory()+"");
						yzService.youzanItemSkuUpdate(youzanItemSkuUpdateParams);
					}else{
						this.logger.info("没有找到库存信息，skuId:"+skuId);
					}
				}else{
					this.logger.info("没有找到对应的有赞sku，skuId:"+skuId);
				}
			}else{
				this.logger.info("商品未上架不能同步库存，skuId:"+skuId);
			}
		}
		
	}



}
